

package com.platform.common.config;

import com.platform.common.core.Result;
import com.platform.common.exception.ApiException;
import com.platform.common.exception.PlatformBindException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义错误处理器
 */
@Controller
@RestControllerAdvice
@Slf4j
public class DefaultExceptionHandlerConfig {


    @ExceptionHandler(BindException.class)
    public ResponseEntity<String> bindExceptionHandler(BindException e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getBindingResult().getFieldErrors().get(0).getDefaultMessage());

    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(PlatformBindException.class)
    public ResponseEntity<String> unauthorizedExceptionHandler(PlatformBindException e) {
        e.printStackTrace();
        return ResponseEntity.status(e.getHttpStatusCode()).body(e.getMessage());
    }

    /**
     * Description : 全局异常捕捉处理
     */
    @ExceptionHandler(ApiException.class)
    public ResponseEntity<Result> apiExceptionHandler(HttpServletRequest req, ApiException e) {
        log.error("ApiException 异常抛出请求地址：{}", req.getRequestURI());
        Result r = new Result();
        r.setMsg(e.getMessage());
        r.setCode(e.getHttpStatusCode());
        return ResponseEntity.status(e.getHttpStatusCode()).body(r);
    }






}